package com.aiyige.page.my.favorite;


import android.content.DialogInterface;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AlertDialog;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.aiyige.R;
import com.aiyige.arouter.config.ARouterConfig;
import com.aiyige.base.BaseActivity;
import com.aiyige.base.eventbus.EventFavoriteUnSelect;
import com.aiyige.model.Subject;
import com.aiyige.track.annotation.Track;
import com.aiyige.utils.AppUtils;
import com.aiyige.utils.KeyboardUtil;
import com.aiyige.utils.widget.MyEditText;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.flyco.tablayout.SlidingTabLayout;

import net.cachapa.expandablelayout.ExpandableLayout;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.LinkedList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by xiachao on 2017/12/4.
 */
@Track("我的收藏")
@Route(path = ARouterConfig.MyFavoritePage, extras = ARouterConfig.EXTRA_NEED_LOGIN)
public class MyFavoritePage extends BaseActivity {

    @BindView(R.id.mainVp)
    ViewPager mainVp;
    @BindView(R.id.tabLayout)
    SlidingTabLayout tabLayout;
    @BindView(R.id.tv_edit)
    TextView tvEdit;

    @BindView(R.id.rl_bottom)
    RelativeLayout llBottom;

    @BindView(R.id.et_search)
    MyEditText inputEt;

    @BindView(R.id.tv_cancel)
    TextView tvCancel;

    @BindView(R.id.cancelLayout)
    ExpandableLayout cancelLayout;

    boolean selectAll = false;

    @BindView(R.id.iv_item_selection)
    ImageView tvSelection;


    private MyPagerAdapter pagerAdapter;

    private boolean isEdit = false;

    private int currentPage = 0;

    public static void start() {
        ARouter.getInstance().build(ARouterConfig.MyFavoritePage).navigation();
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.page_my_favorites);
        ButterKnife.bind(this);
        if (pagerAdapter == null) {
            pagerAdapter = new MyPagerAdapter(getSupportFragmentManager());
        }
        mainVp.setAdapter(pagerAdapter);
        mainVp.setOffscreenPageLimit(pagerAdapter.getCount());
        tabLayout.setViewPager(mainVp);
        mainVp.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                if (isEdit) {
                    setEdit(false);
                }
                currentPage = position;
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });

        inputEt.setActionSearch(new MyEditText.ActionCallback() {
            @Override
            public void actionSearch(String value) {
                SearchMyFavoritePage.start(value);
            }
        });
        inputEt.setEditTextHint(getString(R.string.search));
        AppUtils.addOnSoftKeyBoardVisibleListener(this, new AppUtils.SoftKeyBoardCallback() {
            @Override
            public void show() {
            }

            @Override
            public void hide() {
//                inputEt.getEditText().clearAnimation();
            }
        });
        setAutoRegisterEventBus(true);
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void unSelectCallback(EventFavoriteUnSelect eventFavoriteUnSelect) {
        if (selectAll) {
            selectAll = !selectAll;
            tvSelection.setSelected(selectAll);
        }
    }


    @OnClick({R.id.titleBackBtn, R.id.tv_edit, R.id.ll_select_all, R.id.tv_delete, R.id.tv_cancel})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.titleBackBtn:
                finish();
                break;
            case R.id.tv_edit:
                setEdit(!isEdit);
                break;
            case R.id.ll_select_all:
                selectAll = !selectAll;
                tvSelection.setSelected(selectAll);
                if (selectAll) {
                    setSelectAll();
                } else {
                    setUnSelectAll();
                }
                break;
            case R.id.tv_delete:
                deleteSelected();
                break;
            case R.id.tv_cancel:
                inputEt.getEditText().clearFocus();
                KeyboardUtil.hideKeyboard(this, inputEt);
                inputEt.getEditText().setText("");
                break;
        }
    }

    private void deleteSelected() {
        if (pagerAdapter == null || mainVp == null) {
            return;
        }
        if (!getCurrentDataPage().checkEmptySelectList()) {
            return;
        }
        new AlertDialog.Builder(this).setTitle(getString(R.string.alert_delete))
                .setPositiveButton(getString(R.string.confirm), new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        getCurrentDataPage().deleteSelected();
                        dialog.dismiss();
                    }
                }).setNegativeButton(getString(R.string.cancel), new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        }).show();

    }

    private MyFavoriteDataPage getCurrentDataPage() {
        return (MyFavoriteDataPage) pagerAdapter.getItem(currentPage);
    }

    public class MyPagerAdapter extends FragmentPagerAdapter {
        List<MyFavoriteDataPage> pageList = new LinkedList<>();


        public MyPagerAdapter(FragmentManager fragmentManager) {
            super(fragmentManager);
            pageList.add(MyFavoriteDataPage.newInstance(Subject.activity));
            pageList.add(MyFavoriteDataPage.newInstance(Subject.video_course));
            pageList.add(MyFavoriteDataPage.newInstance(Subject.major_course));
//                        pageList.add(MyFavoriteDataPage.newInstance(Subject.training_course));
//            pageList.add(MyFavoriteDataPage.newInstance(Subject.training_course));
//            pageList.add(MyFavoriteDataPage.newInstance(Subject.training_card));
//            pageList.add(MyFavoriteDataPage.newInstance(Subject.private_course));
        }

        @Override
        public Fragment getItem(int position) {
            return pageList.get(position);
        }

        @Override
        public int getCount() {
            return pageList.size();
        }

        @Override
        public CharSequence getPageTitle(int position) {
            return pageList.get(position).getPageTitle();
        }


    }

    private void setSelectAll() {
        if (pagerAdapter == null || pagerAdapter.pageList == null || pagerAdapter.pageList.isEmpty()) {
            return;
        }
        getCurrentDataPage().selectAll();
    }

    private void setUnSelectAll() {
        if (pagerAdapter == null || pagerAdapter.pageList == null || pagerAdapter.pageList.isEmpty()) {
            return;
        }
        getCurrentDataPage().unSelectAll();
    }

    public void setEdit(boolean edit) {
        isEdit = edit;
        if (pagerAdapter == null || pagerAdapter.pageList == null || pagerAdapter.pageList.isEmpty()) {
            return;
        }
        getCurrentDataPage().setEdit(isEdit);
//        for (MyFavoriteDataPage page : pagerAdapter.pageList) {
//            page.setEdit(isEdit);
//        }
        tvEdit.setText(getString(isEdit ? R.string.cancel_edit : R.string.edit));
        llBottom.setVisibility(isEdit ? View.VISIBLE : View.GONE);
        if (!edit) {
            selectAll = false;
            tvSelection.setSelected(selectAll);
        }
    }


}
